part of 'index.dart';

class SystemNotificationPage extends StatefulWidget {
  const SystemNotificationPage(this.conversation, {super.key});
  final EMConversation conversation;

  @override
  State<SystemNotificationPage> createState() => _SystemNotificationPageState();
}

class _SystemNotificationPageState extends State<SystemNotificationPage> {
  final refreshController = EasyRefreshController(
    controlFinishRefresh: true,
    controlFinishLoad: true,
  );
  List<EMMessage> messageList = [];

  final int _limit = 20;
  bool _noMore = false;
  String? startMsgId;

  @override
  void initState() {
    super.initState();
    _getMessageList();
  }

  Future<void> _getMessageList({String? start}) async {
    final conversationId = widget.conversation.id;
    final result = await ImManager.of.loadLocalHistoryMessage(
      conversationId,
      startMsgId: start ?? startMsgId,
      limit: _limit,
    );
    messageList.addAll(result);
    messageList.sort((a, b) => b.serverTime.compareTo(a.serverTime));
    if (messageList.isNotEmpty) startMsgId = messageList.first.msgId;
    if (result.length < _limit) _noMore = true;
    setState(() {});
  }

  void onLoading() async {
    if (_noMore) {
      refreshController.finishLoad(IndicatorResult.noMore);
      return;
    }
    try {
      await _getMessageList();
      refreshController.finishLoad();
    } catch (error) {
      refreshController.finishLoad(IndicatorResult.fail);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: const Color(0xFFDCD4FF),
        centerTitle: true,
        title: Text(
          T.current.c_sys_notice,
          style: const TextStyle(fontSize: 22, fontWeight: FontWeight.w500),
        ),
      ),
      backgroundColor: const Color(0xFFFAFAFA),
      body: Padding(
        padding: const EdgeInsets.symmetric(horizontal: 15),
        child: CustomPullScrollView(
          controller: refreshController,
          onLoading: onLoading,
          refreshOnStart: false,
          builder: (context, physics) => CustomScrollView(
            physics: physics,
            slivers: [
              if (messageList.isEmpty)
                Padding(
                  padding: const EdgeInsets.only(top: 100),
                  child: Image.asset(
                    Images.bgPlaceEmpty,
                    width: 200,
                    height: 200,
                  ),
                ).sliver,
              SliverList.builder(
                itemBuilder: (context, index) {
                  return _Card(messageList[index]);
                },
                itemCount: messageList.length,
              ),
            ],
          ),
        ),
      ),
    );
  }
}

class _Card extends StatelessWidget {
  const _Card(this.model);
  final EMMessage model;

  @override
  Widget build(BuildContext context) {
    final attributes = model.attributes ?? {};
    final title = attributes['title'];
    final content = attributes['content'];
    final pic = attributes['pic'] as String?;

    return Padding(
      padding: const EdgeInsets.only(top: 15, bottom: 5),
      child: Column(
        children: [
          Container(
            padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 2),
            decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(99),
              color: const Color(0xFF4A4A4A).withOpacity(0.1),
            ),
            child: Text(
              Tools.dateFromMS(model.serverTime),
              style: const TextStyle(color: Colors.white, fontSize: 12),
            ),
          ),
          Container(
            decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(8),
              color: Colors.white,
              boxShadow: [
                BoxShadow(
                  color: const Color(0xFF787878).withOpacity(0.1),
                  spreadRadius: 1,
                  blurRadius: 5,
                  offset: const Offset(4, 0),
                )
              ],
            ),
            margin: const EdgeInsets.only(top: 10),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.stretch,
              children: [
                if (pic?.startsWith('http') == true)
                  Container(
                    height: 160,
                    clipBehavior: Clip.hardEdge,
                    decoration: const BoxDecoration(
                      borderRadius: BorderRadius.vertical(
                        top: Radius.circular(8),
                      ),
                    ),
                    child: image(pic!, fit: BoxFit.fitWidth),
                  ),
                Column(
                  crossAxisAlignment: CrossAxisAlignment.stretch,
                  children: [
                    Text(
                      title ?? '',
                      style: const TextStyle(
                        fontWeight: FontWeight.w500,
                        fontSize: 16,
                      ),
                    ),
                    const SizedBox(height: 8),
                    Text(
                      content ?? '',
                      style: const TextStyle(color: Color(0xFFC1C1C1)),
                    ),
                    const SizedBox(height: 8),
                    const Divider(color: Color(0xFFF2F2F2)),
                    const SizedBox(height: 8),
                    Row(
                      children: [
                        Text(
                          T.current.chat9_click_to_view,
                          style: const TextStyle(
                              color: Color(0xFFA397DE), fontSize: 11),
                        ),
                        const Spacer(),
                        const Icon(
                          Icons.chevron_right,
                          color: Color(0xFFA397DE),
                          size: 15,
                        ),
                      ],
                    )
                  ],
                ).paddingSymmetric(horizontal: 8, vertical: 12),
              ],
            ),
          )
        ],
      ),
    ).onTap(() {
      String? link;
      if (attributes['page'] is Map) {
        final url = attributes['page']['androidRoute'] as String?;
        if (url != null && url.contains('url=')) {
          link = url.split("url=")[1];
        }
      }
      if (link != null) CommonWebView.show(context, link);
    });
  }
}
